export default class WaterMark {
    constructor(params) {
        this.params = Object.assign({
            fontSize: "30px",
            color: "#f1f1f1",
            id: this.randomString(18),
            text: "skyler",
            size: 100,
        }, params);

        this.init()
        this.setSafetyLock();
    }

    init() {
        this.createCanvas();
        this.fillCanvas();
    }
    createCanvas() {

        // 删除已有ID的元素
        let oldCanvas = document.getElementById(this.params.id)

        if (oldCanvas) {
            oldCanvas.parentNode.removeChild(oldCanvas);
        }

        // 创建画布
        let canvas = document.createElement("canvas");
        let width = window.screen.width;
        let height = window.screen.height;

        // 设置画布样式并添加到body上
        canvas.setAttribute("id", this.params.id);
        canvas.width = width;
        canvas.height = height;
        canvas.style.cssText = `width: 100%; height: 100%; position: fixed; top: 0; left: 0; z-index: -1`;

        document.body.appendChild(canvas);
    }
    fillCanvas() {
        /**
         * 填充画布
         * 计算x轴和y轴可展示水印的个数
         * 画布逆时针旋转15度
         * 遍历x, y依次绘制水印
         */
        let canvas = document.getElementById(this.params.id);
        let width = window.screen.width;
        let height = window.screen.height;
        let cxt = canvas.getContext('2d');

        // x轴、y轴方向 负的偏移
        let offx = window.screen.height * Math.tan(15 * Math.PI / 180);
        let offy = window.screen.height * Math.tan(15 * Math.PI / 180);
        console.log(offx, offy)


        let xCount = (width + offx) / this.params.size;
        let yCount = (height + offy) / this.params.size;

        cxt.rotate(Math.PI / 180 * -15);



        for (let i = 0; i < xCount; i++) {
            for (let j = 0; j < yCount; j++) {
                cxt.fillStyle = this.params.color;
                cxt.font = this.params.fontSize + " Arial";
                cxt.fillText(this.params.text, i * this.params.size - offx, j * this.params.size);
            }
        }
    }
    // 生成随机字符串
    randomString(e) {
        let str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        e = e || str.length;
        let ret = "";
        for (let i = 0; i < e; i++) {
            let random = Math.floor(Math.random() * str.length);
            ret += str[random];
            str.replace(str[random], "");
        }
        return ret;
    }
    setSafetyLock() {
        let self = this;
        window.setInterval(() => {
            let canvas = document.getElementById(self.params.id);
            if (!canvas) {
                self.init();
            }
        }, 10);
    }
}








